<script>
import {getCategoryApi} from "@/api/category"
import SearchInput from "@/components/SearchInput.vue"
import TarBar from "@/components/TarBar.vue"
import {getSafeAreaInsets} from "@/utils/safeAreaInsets"

export default {
  name: "Category",
  components: {
    TarBar,
    SearchInput
  },
  created() {
    this.getCategoryList()
  },
  data() {
    return {
      list: [],
      activeIndex: 0
    }
  },
  methods: {
    getSafeAreaInsets,
    // 异步请求的数据最开始在页面上并没有，如果模板使用了还不存在的数据会报错
    async getCategoryList() {
      const {
        data: {
          list
        }
      } = await getCategoryApi()
      this.list = list
    },
    goProduct(item) {
      uni.navigateTo({url: `/pages/SearchList/SearchList?categoryId=${item.category_id}&search=${item.name}`})
    }
  }
}
</script>

<template>
  <div class="category">
    <view class="_header">
      <!-- 分类 -->
      <van-nav-bar title="全部分类"/>

      <SearchInput></SearchInput>
    </view>

    <!-- 分类列表 -->
    <div class="list-box" :style="{height: `calc(100vh - 150px - ${getSafeAreaInsets()})`}">

      <div class="left">
        <ul>
          <li v-for="(item, index) in list" :key="item.category_id">
            <navigator :class="{ active: activeIndex === index }" @click="activeIndex = index" href="javascript:;">
              {{ item.name }}
            </navigator>
          </li>
        </ul>
      </div>

      <!--加个 v-if 防止 list[activeIndex] 最开始拿到 undefined，然后 undefined.children 报错-->
      <div class="right" v-if="list.length">
        <div v-for="item in list[activeIndex].children" :key="item.category_id" @click="goProduct(item)"
             class="cate-goods">
          <image :src="item.image.external_url" alt=""/>
          <view>{{ item.name }}</view>
        </div>
      </div>
    </div>

    <TarBar tabbar-index="1"></TarBar>
  </div>
</template>

<style lang="less">
.category {

  ._header {
    position: sticky;
    top: 0;
  }

  .list-box {
    display: flex;

    .left {
      width: 85px;
      height: 100%;
      background-color: #f3f3f3;
      overflow: auto;

      navigator {
        display: block;
        height: 45px;
        line-height: 45px;
        text-align: center;
        color: #444444;
        font-size: 12px;

        &.active {
          color: #fb442f;
          background-color: #fff;
        }
      }
    }

    .right {
      flex: 1;
      height: 100%;
      background-color: #ffffff;
      display: flex;
      flex-wrap: wrap;
      padding: 10px 0;
      overflow: auto;

      .cate-goods {
        width: 33.3%;
        margin-bottom: 10px;

        image {
          width: 70px;
          height: 70px;
          display: block;
          margin: 5px auto;
        }

        view {
          text-align: center;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
